const db = require('../../db/sql')
const {floor} = require("lodash");

function modifyRole(params, res) {
    console.log(params, '55')
    let roleId = params.role_id;

    let permissionIds = Array.from(params.permissions);
    //当没有选择一级菜单下的所有子功能菜单，为了能正常显示菜单，必须把一级菜单加上
    permissionIds.forEach((o, i, permissionIds) => {
        //大于10表示不是一级菜单
        if (o > 10) {
            if (permissionIds.includes(floor(o / 10))) {

            } else {
                permissionIds.push(floor(o / 10))
                permissionIds = Array.from(new Set(permissionIds))
            }

        }
    })
    console.log(permissionIds, 'idssahi')
    let deleteSql = `DELETE FROM role_permission WHERE role_id = ${roleId}`;
    db.query(deleteSql, (err, result) => {
        if (err) {
            console.log(err);
            res.json({
                status: '1',
                msg: err.message
            });
        } else {
            let sql = `INSERT INTO role_permission(role_id, rank_id) VALUES`;
            permissionIds.forEach((id) => {
                sql += `(${roleId}, ${id}),`;
            });
            //去除最后一个的逗号
            sql = sql.slice(0, -1);
            console.log(permissionIds, sql, 'sql语句')
            db.query(sql, (err, result) => {
                if (err) {
                    console.log(err);
                    res.json({
                        status: '1',
                        msg: err.message
                    });
                } else {
                    res.json({
                        status: '200',
                        msg: 'success'
                    });
                }
            });
        }
    });
}

module.exports = modifyRole
